<!DOCTYPE html>
<html>

<head>
  <title>cannon.js - callbacks demo</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/style.css" type="text/css" />
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>

<body>
  <script src="../../feng3d/out/feng3d.js"></script>
  <script src="../out/cannon.js"></script>
  <script src="../build/cannon.demo.js"></script>
  <script src="../libs/dat.gui.js"></script>
  <script src="../libs/Three.js"></script>
  <script src="../libs/TrackballControls.js"></script>
  <script src="../libs/Detector.js"></script>
  <script src="../libs/Stats.js"></script>
  <script src="../libs/smoothie.js"></script>
  <script>

    /**
     * A demo showing how to use the preStep callback to add a force to a body.
     * This will act like a force field.
     */

    var demo = new CANNON.Demo();

    demo.addScene("Moon", function ()
    {
      var world = demo.getWorld();

      var mass = 5;
      var moonShape = new CANNON.Sphere(0.5);
      var planetShape = new CANNON.Sphere(3.5);
      var moon = new CANNON.Body({
        mass: mass,
        position: new CANNON.Vector3(5, 0, 0)
      });
      moon.addShape(moonShape);
      var planet = new CANNON.Body({ mass: 0 });
      planet.addShape(planetShape);

      moon.velocity.set(0, 0, 8);
      moon.linearDamping = 0.0;

      // Use the preStep callback to apply the gravity force on the moon.
      // This callback is evoked each timestep.
      moon.preStep = function ()
      {

        // Get the vector pointing from the moon to the planet center
        var moon_to_planet = new CANNON.Vector3();
        this.position.negateTo(moon_to_planet);

        // Get distance from planet to moon
        var distance = moon_to_planet.length;

        // Now apply force on moon
        // Fore is pointing in the moon-planet direction
        moon_to_planet.normalize();
        moon_to_planet.scaleNumberTo(1500 / Math.pow(distance, 2), this.force);

      }

      // We add the objects to the world to simulate them
      world.addBody(moon);
      world.addBody(planet);

      // And we add them to the demo to make them visible
      demo.addVisual(moon);
      demo.addVisual(planet);
    });

    demo.start();

  </script>
</body>

</html>